import { defineStore } from "pinia";
import { ref, getCurrentInstance } from "vue";
import socket from "./socket"
export const useLoginStore = defineStore("login", () => {
    let menulist = ref([])
    let checkmenu = ref("首页")

    // 获取全局 axios 实例
    const app = getCurrentInstance();
    const axios = app?.proxy?.$axios;

    // 初始化socket连接并监听消息
    socket.on("menuUpdated", (newMenu) => {
        console.log("Menu updated:", newMenu);
        menulist.value = newMenu;  // 更新菜单列表
    });


    const upceckmenu = (val) => {
        checkmenu.value = val
    }

    async function getMenu() {
        const roleid = localStorage.getItem('roleid');
        const _id = roleid === "admin" ? "6641c6cbd507a2e500279920" : "6641c75ad507a2e500279922";
        let { data: { data } } = await axios.get("/getmenulist", { params: { _id } })
        let newdata = data.filter(item => item.rank !== 0)
        newdata.sort((a, b) => {
            return a.rank - b.rank
        })
        menulist.value = newdata
    }

    return { menulist, checkmenu, getMenu, upceckmenu }
})